package com.example.springboot_sdse_air.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot_sdse_air.entity.SystemPdfFavorite;
import com.example.springboot_sdse_air.mapper.SystemPdfFavoriteMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * 功能：系统PDF收藏服务类
 * 作者：王彬 202200111149
 * 日期：2025-01-15
 */
@Service
public class SystemPdfFavoriteService extends ServiceImpl<SystemPdfFavoriteMapper, SystemPdfFavorite> {

    @Resource
    SystemPdfFavoriteMapper systemPdfFavoriteMapper;

    /**
     * 获取用户收藏的PDF ID列表
     */
    public List<Integer> getFavoritePdfIds(Integer userId) {
        return systemPdfFavoriteMapper.getFavoritePdfIds(userId);
    }

    /**
     * 检查用户是否收藏了指定PDF
     */
    public boolean isFavorited(Integer userId, Integer pdfId) {
        return systemPdfFavoriteMapper.isFavorited(userId, pdfId);
    }

    /**
     * 切换收藏状态
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleFavorite(Integer userId, Integer pdfId) {
        // 检查是否已收藏
        boolean isFavorited = isFavorited(userId, pdfId);
        
        if (isFavorited) {
            // 取消收藏
            return removeFavorite(userId, pdfId);
        } else {
            // 添加收藏
            return addFavorite(userId, pdfId);
        }
    }

    /**
     * 添加收藏
     */
    private boolean addFavorite(Integer userId, Integer pdfId) {
        SystemPdfFavorite favorite = new SystemPdfFavorite();
        favorite.setUserId(userId);
        favorite.setPdfId(pdfId);
        favorite.setCreateTime(new Timestamp(System.currentTimeMillis()));
        
        return this.save(favorite);
    }

    /**
     * 取消收藏
     */
    private boolean removeFavorite(Integer userId, Integer pdfId) {
        return this.remove(
            this.lambdaQuery()
                .eq(SystemPdfFavorite::getUserId, userId)
                .eq(SystemPdfFavorite::getPdfId, pdfId)
                .getWrapper()
        );
    }
} 